<?php
header("Content-Type: application/json;charset=utf-8");

// 判断token是否存在
if (!@$_GET["token"]) {
    http_response_code(400);
    die(json_encode(array(
        "status" => false,
        "msg" => "博士，请提供您的token，不然...阿米娅很难办..."
    ), JSON_UNESCAPED_UNICODE));
}

// 引入class
include_once ($_SERVER["DOCUMENT_ROOT"]."/main.class.php");
$main = new main();

// 保存用户信息
$user_info = $main->getUserInfo($_GET["token"]);
$user_info_UID = $user_info['data']['uid'];// 用户UID
$user_info_nickName = $user_info['data']['nickName'];// 用户名字
$gacha_token = $main->ifUrl($_GET["token"]);// encode和decode两份token
$user_json_path = __DIR__.'/data/'.$user_info_UID.'.json';// JSON文件路径

// 判断是否有data目录
if (array_search('data',scandir(__DIR__),true)) {
    // 判断是否有已经有用户数据
    if (array_search($user_info_UID.'.json',scandir(__DIR__.'/data'),true)){
        $user_json = json_decode(file_get_contents($user_json_path),true);
        $gacha_output_file = $user_json;
    }
}else {
    mkdir('data',0777,true);
}
$file_last_gacha_time = $user_json["0"]["time"] ?? 0;// 未获取到则设为0

// 获取抽卡数据
$gacha_max_pages = 15;// 最大页数
$gacha_origin = array();// 抽卡数据API返回的内容
// 向鹰角请求数据
for($gacha_pages = 1;$gacha_pages <=$gacha_max_pages;$gacha_pages++) {
    $gacha_origin[] = json_decode(file_get_contents("https://ak.hypergryph.com/user/api/inquiry/gacha?page=$gacha_pages&token={$gacha_token["encode"]}"),true);
    if (empty($gacha_origin[$gacha_pages-1]["data"]["list"])) {
        // 删除最后一个无数据数组
        array_pop($gacha_origin);
        break;
    };
    if (empty($gacha_origin)) {
        http_response_code(400);
        echo json_encode(array(
            "status" => false,
            "msg" => "博士，似乎出现了一些问题，获取到的抽卡数据为空，是..阿米娅没做好吗？"
        ));
        break;
    }
}

// 判断鹰角返回信息。当token正确，但是鹰角获取抽卡API维护时会需要该判断
if(!empty($gacha_origin[0]['msg'])) {
    http_response_code(400);
    echo json_encode(array(
        "status" => false,
        "msg" => "博士，遇到紧急状况，鹰角网络API返回信息：".$gacha_origin[0]["msg"]."，错误代码：".$gacha_origin[0]["code"]."，怎么办...这已经超出阿米娅能操作的范围。"
    ),JSON_UNESCAPED_UNICODE);
    die;
}

// 输出文件的变量
$gacha_output_file = $gacha_output_file ?? array(
        'uid' => $user_info_UID,// UID
        'nickName' => $user_info_nickName,// 昵称
    );

// 卡池
$gacha_temp = array();// 缓存

// 遍历获取的数据
foreach ($gacha_origin as $val) {
    // 遍历第一层 遍历页数
    foreach ($val["data"]["list"] as $val2) {
        // 遍历第二层 每一页中的每一抽
        $gacha = array();// 暂时存放每一抽
        foreach ($val2["chars"] as $val3) {
            // 遍历每一单抽或每十连抽
            $gacha[] = array(
                "time" => $val2["ts"],// 写入抽卡时间
                "name" => $val3["name"],// 写入抽到的角色名
                "rarity" => $val3["rarity"]+1,// 写入抽到角色的稀有度
                "pool" => $val2["pool"],// 写入抽的卡池
                "isNew" => $val3["isNew"]// 写入是否抽到的是新角色
            );
        }
        // 判断是否是十连抽，十连需倒序才复合游戏内抽卡顺序
        if (!empty($gacha)) {
            if ($gacha["0"]["time"] > $file_last_gacha_time) {
                if (!count($gacha)) {
                    $gacha_temp[] = $gacha;
                }else {
                    $gacha = array_reverse($gacha);
                    foreach ($gacha as $val4) {
                        $gacha_temp[] = $val4;
                    }
                    unset($val4);
                }
            }
        }
        unset($val3);

    }
    unset($gacha);
    unset($val2);
}

unset($val);

// 写入到输出文件变量
$gacha_output_file = array_merge($gacha_temp, $gacha_output_file);

// 文件输出
file_put_contents($user_json_path, json_encode($gacha_output_file, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

// 需要处理的数据(JSON)
$un_analysis_json = array_reverse($gacha_output_file);
unset($un_analysis_json["uid"],$un_analysis_json["nickName"]);

// 统计抽过的卡池
$gacha_pool = array(
    "所有卡池"
);
foreach ($un_analysis_json as $val) {
    // 统计所有抽过的卡池
    if (!in_array($val["pool"],$gacha_pool)){
        $gacha_pool[] = $val["pool"];// 将卡池名写入到卡池统计中
    }
}
unset($val);

// 处理输出模板
$res_gacha = array(
    "uid" => $user_info_UID,// 用户UID
    "nickName" => $user_info_nickName,// 用户昵称
    "pool" => $gacha_pool,// 卡池列表
    "newDataNum" => count($gacha_temp)// 新获取的数据
);

// 处理数据
foreach ($gacha_pool as $pool_name){
    $res_gacha[$pool_name] = array(
        "firstGacha" => 0,// 第一次抽卡时间
        "gachaLastR6Num" => 0,// 距离上次六星出货次数
        "gachaLastR5Num" => 0,// 距离上次五星出货次数
        "gachaNum" => 0,// 该卡池抽卡次数
        "lastGacha" => 0,// 最后一次抽卡时间
        "poolName" => "",// 该卡池名
        "r3Num" => 0,// 三星数量
        "r4Num" => 0,// 四星数量
        "r5History" => array(),// 五星历史
        "r5Num" => 0,// 五星数量
        "r5Avg" => 0,// 五星平均出货次数
        "r6History" => array(),// 六星历史
        "r6Num" => 0,// 六星数量
        "r6Avg" => 0// 六星平均出货次数
    );

    // 定义短名变量
    $firstGacha = 0;
    $lastGacha = 0;
    $gachaLastR6Num = 0;
    $gachaLastR5Num = 0;
    $gachaNum = 0;
    $r3Num = 0;
    $r4Num = 0;
    $r5Num = 0;
    $r5Avg = 0;
    $r6Num = 0;
    $r6Avg = 0;
    foreach ($un_analysis_json as $val) {
        if ($val["pool"] == $pool_name || $pool_name == "所有卡池"){
            // 写入该卡池第一抽
            if (empty($firstGacha)) {
                $firstGacha = $val["time"];
            }

            // 写入该卡池最后一抽
            if (empty($lastGacha)) {
                $lastGacha = $val["time"];
            }else{
                $lastGacha = max($lastGacha, $val["time"]);
            }

            $gachaNum++;
            $gachaLastR6Num++;
            $gachaLastR5Num++;
            // 稀有度判断
            switch ($val["rarity"]){
                case "6":
                    $r6Num++;
                    $val["gachaNum"] = $gachaLastR6Num;// 写入距离上次五星抽卡次数
                    $gachaLastR6Num = 0;// 抽到六星就把距离上次六星抽卡计数器归零
                    array_unshift($res_gacha[$pool_name]["r6History"],$val);

                    // 防止除数为零
                    $r6Num2 = $r6Num == 0 ? 1 : $r6Num;
                    // 每一次出货，再计算一次平均出货率，不出货不计算
                    $r6Avg = round($gachaNum  / $r6Num2,2);
                    break;
                case "5":
                    $r5Num++;
                    $val["gachaNum"] = $gachaLastR5Num;// 写入距离上次五星抽卡次数
                    $gachaLastR5Num = 0;// 抽到五星就把距离上次六星抽卡计数器归零
                    array_unshift($res_gacha[$pool_name]["r5History"],$val);

                    // 防止除数为零
                    $r5Num2 = $r5Num == 0 ? 1 : $r5Num;
                    // 每一次出货，再计算一次平均出货率，不出货不计算
                    $r5Avg = round($gachaNum  / $r5Num2,2);
                    break;
                case "4":
                    $r4Num++;
                    break;
                case "3":
                    $r3Num++;
                    break;
            }
        }
    }
    unset($val);
    $res_gacha[$pool_name]["poolName"] = $pool_name;
    $res_gacha[$pool_name]["firstGacha"] = $firstGacha;
    $res_gacha[$pool_name]["lastGacha"] = $lastGacha;
    $res_gacha[$pool_name]["gachaLastR6Num"] = $gachaLastR6Num;
    $res_gacha[$pool_name]["gachaLastR5Num"] = $gachaLastR5Num;
    $res_gacha[$pool_name]["gachaNum"] = $gachaNum;
    $res_gacha[$pool_name]["r3Num"] = $r3Num;
    $res_gacha[$pool_name]["r4Num"] = $r4Num;
    $res_gacha[$pool_name]["r5Num"] = $r5Num;
    $res_gacha[$pool_name]["r5Avg"] = $r5Avg;
    $res_gacha[$pool_name]["r6Num"] = $r6Num;
    $res_gacha[$pool_name]["r6Avg"] = $r6Avg;
}
unset($pool_name,$firstGacha,$lastGacha,$gachaLastR6Num,$gachaLastR5Num,$gachaNum,$r3Num,$r4Num,$r5Num,$r5Avg,$r6Num,$r6Avg);



echo json_encode($res_gacha, JSON_UNESCAPED_UNICODE);